//
//  LoginBasicViewController.m
//  Arts1
//
//  Created by 孤星晨宇 on 15/9/14.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "LoginBasicViewController.h"
#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "AllHeader.h"
#import "AppDelegate.h"
#import "WXApi.h"
#import "UserInformationModel.h"
#import "PasswordViewController.h"

@interface LoginBasicViewController ()<UITextFieldDelegate,WXLoginDelegate>

// 登陆直界面的视图控制器   
@property (nonatomic, strong) LoginViewController *loginVC;

// 模糊视图
@property (nonatomic, strong) UIVisualEffectView *visualeffectview;

// 免费注册按钮
@property (nonatomic, strong) UIButton *freeregistBTN;

// 用户信息model类
@property (nonatomic ,strong) UserInformationModel *userModel;


@end

@implementation LoginBasicViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    // Do any additional setup after loading the view.
    [self createVisualEffectView];
    [self createLoginView];
    
    // 创建应用程序代理对象，设置代理
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.delegate = self;
}

// 毛玻璃效果
- (void)createVisualEffectView{
    UIVisualEffect *lightBlurEffect = [UIBlurEffect effectWithStyle:(UIBlurEffectStyleDark)];
    _visualeffectview = [[UIVisualEffectView alloc] initWithEffect:lightBlurEffect];
    _visualeffectview.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    [self.view addSubview:_visualeffectview];
}

//  创建登陆页面
- (void)createLoginView{
    _loginVC = [[LoginViewController alloc] init];
    _loginVC.view.frame = CGRectMake((SCREEN_WIDTH - 267)/ 2.0 , (SCREEN_HEIGHT - 438)/2.0, 267, 350);
    _loginVC.view.layer.cornerRadius = 10;
    //  对登录卡加阴影
    [_loginVC.view.layer setShadowColor:[UIColor blackColor].CGColor];
    [_loginVC.view.layer setShadowOffset:(CGSizeMake(1, 2))];
    [_loginVC.view.layer setShadowOpacity:0.4];
    
    [UIView viewShadowColor:_loginVC.view];
    __weak LoginBasicViewController *loginBVC = self;
    _loginVC.loginblock = ^void(NSInteger index){
        switch (index) {
            case 1: // 点击登陆按钮
                [loginBVC clickLoginButton];
                break;
            case 2: // 记住我的状态
             
                break;
            case 3: // 找回密码
            
                break;
            case 4: // 微信登陆
                [loginBVC clickIncognitoLoginButton];
                break;
            default:
                break;
        }
    };
    [self.view addSubview:_loginVC.view];

    //  免费登录注册
    _freeregistBTN = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _freeregistBTN.frame = CGRectMake((SCREEN_WIDTH - 98)/ 2.0 , _loginVC.view.bottom + 35, 98, 28);
    [_freeregistBTN setTitle:@"免费注册" forState:(UIControlStateNormal)];
    _freeregistBTN.layer.borderColor = [UIColor whiteColor].CGColor;
    _freeregistBTN.layer.cornerRadius = 2;
    _freeregistBTN.layer.masksToBounds = YES;
    _freeregistBTN.layer.borderWidth = 1;
    [_freeregistBTN addTarget:self action:@selector(freeRegister:) forControlEvents:(UIControlEventTouchUpInside)];
     [self.view addSubview:_freeregistBTN];
    
    _findPassword = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _findPassword.frame = CGRectMake((SCREEN_WIDTH - 44)/ 2.0 , _freeregistBTN.bottom + 15, 44, 11);
    [_findPassword  setTitle:@"忘记密码" forState:(UIControlStateNormal)];
    _findPassword.titleLabel.font = [UIFont systemFontOfSize:11];
    _findPassword.layer.borderWidth = 0;
    [_findPassword addTarget:self action:@selector(clickFindPasswordButton:) forControlEvents:(UIControlEventTouchUpInside) ];
    [self.view addSubview:_findPassword];

}

//  点击登陆
- (void)clickLoginButton{
    if (_showbarblock) {
        _showbarblock();
    }
}


//  找回密码
- (void)clickFindPasswordButton:(UIButton *)btn{
    PasswordViewController *passwordVC = [[PasswordViewController alloc] init];
    [self.navigationController pushViewController:passwordVC animated:YES];

}

#pragma mark - 微信授权登陆三步
//点击微信登陆
- (void)clickIncognitoLoginButton{

    [self sendAuthRequest];
}

#pragma mark -- WXLoginDelegate
- (void)getUserInformationWithCode:(NSString *)code
{
    [self getAccess_token:code];
}

//第一步，获取code，这个用来获取token，第二步，就是带上code获取token，第三步，根据第二步获取的token和openid来获取用户的相关信息；
#pragma mark - 微信授权登陆第一步
-(void)sendAuthRequest
{
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo,snsapi_base" ;
    req.state = @"0744" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}
#pragma mark - 微信授权登陆第二步
//第二步，就是带上code获取token，根据请求获取token和openid

-(void)getAccess_token:(NSString *)code
{
    // 登录成功后进入主页面
    [self clickLoginButton];
   
    NSString *wxURL = @"https://api.weixin.qq.com/sns/oauth2/access_token";
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //请求参数:appid---应用唯一标识，在微信开放平台提交应用审核通过后获得;secret---应用密钥AppSecret，在微信开放平台提交应用审核通过后获得;code---填写第一步获取的code参数;grant_type---填authorization_code       四个参数都是必要参数
    NSDictionary *pardic = @{@"appid":@"wx35ed95caedc388d2",@"secret":@"eb8e6d76ed71c1ab30a44d84ca114655",@"code":code,@"grant_type":@"authorization_code"};
    
    [manage GET:wxURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (responseObject) {
             // 请求成功的时候调用这个block
            NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
            NSString *openId = [dic objectForKey:@"openid"];
             [self getUserInfoWithToken:[dic objectForKey:@"access_token"] OpenID:openId];
         //   NSLog(@"微信登陆第二步获取access_token: %@",dic);
             
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
  
}

/**
 *  第三步： 根据第二步获取的token和openid获取用户的相关信息。
 */
- (void)getUserInfoWithToken:(NSString *)token OpenID:(NSString *)openid
{
    NSString *userURL = @"https://api.weixin.qq.com/sns/userinfo";
    
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes  =[NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //请求参数:
    NSDictionary *pardic = @{@"access_token":token,@"openid":openid};
    
    [manage GET:userURL parameters:pardic
        success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if (responseObject) {
             // 请求成功的时候调用这个block
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
             [[NSUserDefaults standardUserDefaults] setObject: dic forKey:@"weixinLogin"];
             self.userModel = [[UserInformationModel alloc] init];
             [_userModel setValuesForKeysWithDictionary:dic];

           
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         // 请求失败的时候调用调用这个block
         NSLog(@"请求失败");
     }];
}


// 免费注册
- (void)freeRegister:(UIButton *)btn{
    RegisterViewController *registVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registVC animated:YES];
}

// 点击空白区域取消编辑
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
